<?php
/***********************************
* @author zolunX10@hotmail.com
* @require ThinkPHP.Model
* @description 链式调用以产生ThinkPHP.Model所需要的where子句
************************************/
class WhereMachine{
    private $lastLogic='AND';
    protected $map=null;
    public function WhereMachine($map=null){
        $this->reset($map);
    }
    public function get(){
        return $this->map;
    }
    public function reset($map=null){
        if (!$map){
            $this->lastLogic='AND';
            $this->map=array('_logic'=>$this->lastLogic);
        } else{
            $this->map =$map;
            $this->lastLogic= $map['_logic'];
        }
        return $this;
    }
    /****
    * simplified method to config map
    */
    public function &set($key, $value=null){
        if (is_null($value)){
            return $this;
        } else if (is_array($value) && is_null($value[1])){
            return $this;
        }
        if (array_key_exists($key, $this->map) ) {
            //已有重名条件存在
        } else {
            
        }
            $this->map[$key]= $value;
        return $this;
    }
    /****
    * 组装复杂条件时使用, 一般用.set就可以了
    */
    public function &chain($data, $logic='AND', $args=null){
        $logic= strtoupper($logic);
        if (is_object($data)){
            $data= $data->get();
        }
        
        if (false!==strpos($logic, 'OR')){
        } else if(false!==strpos($logic, 'NOT')){
        } else{
            $logic= 'AND';
        }
        if (strpos($this->lastLogic, $logic) !==false){
            // the same with last logic
            $this->setMap($data);
        } else{
            $this->map['_complex']= $this->map;
            $this->map['_logic']= $logic;
            $this->setMap($data);
            $this->lastLogic= $logic;
        }
        return $this;
    }
    protected function setMap(&$map){
        foreach($map as $key=>$value){
            $this->map[$key]= $value;
        }
        return $this;
    }
}
?>